import { UseFilters } from '@nestjs/common';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { GrpcFilter } from 'src/common/grpc/grpc.filter';
import { Category } from './category.entity';
import { GrpcService } from 'src/common/grpc/grpc.service';

@UseFilters(GrpcFilter)
@Resolver(() => Category)
export class CategoryResolver {
  constructor(private readonly grpcService: GrpcService) {}

  @Mutation(() => Category)
  async createCategory(@Args('name') name: string): Promise<Category> {
    const c = new Category();
    const pbc = await this.grpcService.service
      .createCategory({ ID: 0, name, problems: [] })
      .toPromise();
    c._id = pbc.ID;
    c.name = pbc.name;
    c.problems = [];
    return c;
  }

  @Mutation(() => Boolean)
  async removeCategory(@Args('_id') _id: number): Promise<boolean> {
    this.grpcService.service.removeCategory({ ID: _id });
    return true;
  }

  @Query(() => [Category])
  async categories(): Promise<Category[]> {
    const pbc = (await this.grpcService.service.getCategories({}).toPromise()).value;

    return pbc.map((pbc) => {
      return {
        _id: pbc.ID,
        name: pbc.name,
        problems: pbc.problems.map((pbp) => {
          return {
            _id: pbp.ID,
            ...pbp,
          };
        }),
      };
    });
  }
}
